#!/bin/bash

# 检查参数数量
if [ $# -lt 2 ]; then
    echo "用法: $0 <版本号> <要编译的组件> [组件2] [组件3] ..."
    echo "可用组件: app, nginx, api, consumer, all"
    echo "示例: $0 0.0.1 app"
    echo "示例: $0 0.0.1 app nginx"
    echo "示例: $0 0.0.1 all"
    exit 1cd
fi

VERSION=$1
shift
COMPONENTS=$@
DIR=$(pwd)

# 如果没有指定组件或指定了all，则编译所有组件
if [ -z "$COMPONENTS" ] || [ "$COMPONENTS" = "all" ]; then
    COMPONENTS="app nginx api consumer"
fi

# 检查是否包含某个组件
contains_component() {
    for comp in $COMPONENTS; do
        if [ "$comp" = "$1" ]; then
            return 0
        fi
    done
    return 1
}

# 编译app
if contains_component "app"; then
    echo "开始编译 app 组件..."
    cd $DIR/web/app
    pnpm install
    pnpm run build
    docker build -f Dockerfile -t swr.cn-east-3.myhuaweicloud.com/cloud-mdgx/sealog/sealog-wiki-app:v$VERSION .
    echo "app 组件编译完成"
fi

# 编译nginx (admin)
if contains_component "nginx"; then
    echo "开始编译 nginx (admin) 组件..."
    cd $DIR/web/admin
    pnpm install
    pnpm run build
    docker build -f Dockerfile -t swr.cn-east-3.myhuaweicloud.com/cloud-mdgx/sealog/sealog-wiki-nginx:v$VERSION .
    echo "nginx (admin) 组件编译完成"
fi

# 编译api
if contains_component "api"; then
    echo "开始编译 api 组件..."
    cd $DIR/backend
    docker buildx build --platform linux/amd64 --tag swr.cn-east-3.myhuaweicloud.com/cloud-mdgx/sealog/sealog-wiki-api:v$VERSION --build-arg VERSION=latest --output type=docker --progress plain --file Dockerfile.api .
    echo "api 组件编译完成"
fi

# 编译consumer
if contains_component "consumer"; then
    echo "开始编译 consumer 组件..."
    cd $DIR/backend
    docker buildx build --platform linux/amd64 --tag swr.cn-east-3.myhuaweicloud.com/cloud-mdgx/sealog/sealog-wiki-consumer:v$VERSION --build-arg VERSION=latest --output type=docker --progress plain --file Dockerfile.consumer .
    echo "consumer 组件编译完成"
fi

echo "编译任务完成!"
